#include "mc920.h"

GrayImage *LinearFilter(GrayImage *I, AdjList *A)
{
  int xp,yp,xq,yq,i;
  float val,wsum;
  GrayImage *J=CreateGrayImage(I->nx,I->ny);

  wsum=0.0;
  for (i=0; i < A->n; i++) 
    wsum += fabs(A->adj[i].w);
  
  for (yp=0; yp < J->ny; yp++) {
    for (xp=0; xp < J->nx; xp++) {
      val = 0.0;
      for (i=0; i < A->n; i++) {
	xq = xp + A->adj[i].dx;
	yq = yp + A->adj[i].dy;
	if ((xq >= 0)&&(xq < J->nx)&&(yq >= 0)&&(yq < J->ny)) 
	  val += I->val[yq][xq]*A->adj[i].w;
      }
      //      J->val[yp][xp] = (int)((val/wsum)+0.5);
      J->val[yp][xp] = (int)((val)+0.5);
    }
  }


  return(J);
}

int main(int argc, char **argv) {
  GrayImage *I,*J;
  AdjList   *A;

  if ((argc!=3)&&(argc!=2)) {
    fprintf(stderr,"usage: linearfilter <image> <kernel>\n");
    fprintf(stderr,"image:  arquivo de imagem pgm\n");    
    fprintf(stderr,"kernel (opcional): arquivo com a lista de adjacentes e pesos\n");    
    exit (-1);
  }

  I = ReadGrayImage(argv[1]);
  if (argc==3)
    A = ReadAdjList(argv[2]);
  else
    A = CircularGaussian(10.0);
  J = LinearFilter(I,A);
  WriteGrayImage(J,"filtered.pgm");

  DestroyGrayImage(&I);
  DestroyGrayImage(&J);
  DestroyAdjList(&A);


  return 0;
}

